package com.ys.controller.api.storage;

import com.alibaba.fastjson.JSON;
import com.ys.config.MenuId;
import com.ys.entity.finance.TcwWanliPrepaymentPooling;
import com.ys.entity.storage.TccFbaDeliverItem;
import com.ys.entity.storage.TccLogisticsComprehensive;
import com.ys.entity.sys.YsCol;
import com.ys.service.storage.TccLogisticsReconcileService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Author: fxz
 * @CreateTime: 2025-03-04
 * @Description: 物流对账控制层
 * @Version: 1.0
 */
@Controller
@RequestMapping("/api/inter/tccLogisticsReconcile")
public class ApiInterTccLogisticsReconcileController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTccLogisticsReconcileController.class);

    @Autowired
    private CommonApiService<TccLogisticsComprehensive> commonApiService;

    @Autowired
    private TccLogisticsReconcileService tccLogisticsReconcileService;

    //菜单id
    private Long menuId = MenuId.TCC_LOGISTICSRECONCILE;

    //权限字符
    private final String PERMISSIONS_VIEW = "tccLogisticsReconcile:view";
    private final String PERMISSIONS_APIDZ = "tccLogisticsReconcile:apiDz";

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccLogisticsComprehensive setSeachSql(TccLogisticsComprehensive cond){
        cond
                .addLeftJoin("TCC_LogisticsChannelMaint B ON B.id = A.LogChannelId")
                .addLeftJoin("TCC_LogisticsServiceProvider C ON C.ProviderBid = B.ProviderCode")
                .addField("C.Name serviceName")
                .addField("C.id serviceId")
                .addField("A.status _ys_status")
                .setOrderby("A.id DESC");//排序
        ;
        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }

    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TccLogisticsComprehensive cond, String conditions){
        cond = setSeachSql(cond);
        //物流状态
        String _ys_status = ConditionUtil.getConditionValue(conditions, "_ys_status");
        if(_ys_status == null){
            //默认查询待对账和关税状态不为已关税
            cond.where("A.status = 3 OR A.tariffZfStatus = 1");
        }else if (!_ys_status.equals("1001")){
            cond.where("A.status = " + _ys_status);
        }else {
            cond.where("A.status >= 3");
        }
        //创建时间
        String _ys_createTime = ConditionUtil.getConditionValue(conditions, "_ys_createTime");
        if (_ys_createTime != null && _ys_createTime.length() > 0) {
            String[] timeDays = _ys_createTime.split(" ~ ");
            cond.where("A.CreateTime >= '" + timeDays[0] + "' and A.CreateTime <= '" + timeDays[1] + "'");
        }
        //物流订单利润率（对账）
        String _ys_logOrderMarginDz = ConditionUtil.getConditionValue(conditions, "_ys_logOrderMarginDz");
        if (_ys_logOrderMarginDz != null){
            if (_ys_logOrderMarginDz.equals("0")){
                //正
                cond.where("A.logOrderMarginDz >=0");
            }else {
                //负
                cond.where("A.logOrderMarginDz <0");
            }
        }
        //物流订单对账说明
        String _ys_logOrderlDesDz = ConditionUtil.getConditionValue(conditions, "_ys_logOrderlDesDz");
        if (_ys_logOrderlDesDz != null){
            if (_ys_logOrderlDesDz.equals("0")){
                cond.where("A.logOrderlDesDz IS NOT NULL AND A.logOrderlDesDz != ''");
            }else {
                cond.where("A.logOrderlDesDz IS NULL OR A.logOrderlDesDz = ''");
            }
        }

        LayuiTableVoJA vo = commonApiService.searchLay(cond);
        return vo;
    }

    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/searchZb")
    @ResponseBody
    public LayuiTableVoJA searchZb(@ModelAttribute TccLogisticsComprehensive cond, String rowConditions){
        TccLogisticsComprehensive tccLogisticsComprehensive = JSON.parseObject(rowConditions, TccLogisticsComprehensive.class);
        TccFbaDeliverItem tccFbaDeliverItem = new TccFbaDeliverItem().setId(tccLogisticsComprehensive.getFbaDeliverItemId()).queryFirst();
        cond.addLeftJoin("TCC_FbaDeliverSon B ON B.Pbid = A.fbaDeliverBid ")
                .addField("B.boxNo")//箱号
                .addLeftJoin("TCC_FbaDeliverItem DD ON DD.id = B.FbaDeliverItemId ")
                .addLeftJoin("TCC_FbaBox D ON D.id = B.FbaBoxId ")
                .addField("(CONVERT(varchar(10), cast(D.BoxLong as float)) + '*' + CONVERT(varchar(10), cast(D.BoxWide as float))  + '*' + CONVERT(varchar(10), cast(D.BoxHigh as float))) dimensionsCase")//箱尺寸
                .addField("D.boxWeight")//箱重量
                .addLeftJoin("TCC_FbaBoxDetail C ON C.BoxId = D.id ")
                .addField("C.num")//箱中数量
                .addField("C.purchaseAmount priceIn")//商品采购价
                .addLeftJoin("TCC_FbaBoxUpItem H ON H.id = C.BoxUpItemId ")
                .addField("H.AverageBoxUpNum averageBoxNum")
                .addField("H.goodsLink goodsLink")
                .addField("H.averageBoxUpNum averageBoxUpNum")
                .addLeftJoin("TCC_FbaPlanItem I ON I.id = H.FbaPlanItemId")
                .addField("I.commodityCode,I.commodityName,I.sku,I.numStock,I.numPlanDeliver,I.isSign,I.signCode,I.annexFile,I.asin,I.fnSku,I.codeGoodsHs,I.nameGoodsCn")
                .addField("I.nameMaterialCn,I.weightPackage,I.vck,I.vkq,I.vhw,I.numApiDeliver")
                .addField("(CONVERT(varchar(19), cast(I.lengthPackage as float)) + '*' + CONVERT(varchar(19), cast(I.widthPackage as float))  + '*' + CONVERT(varchar(19), cast(I.heightPackage as float))) packageSize")
                .setOrderby("A.id DESC");//排序
        if (tccLogisticsComprehensive != null) {
            cond.where("DD.FbaBoxUpInfoId = " + tccFbaDeliverItem.getFbaBoxUpInfoId());
        }
        LayuiTableVoJA vo = commonApiService.searchLay(cond);
        return vo;
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccLogisticsComprehensive cond, String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //物流状态
            String status = ConditionUtil.getConditionValue(conditions, "status");
            if(status == null){
                //默认查询待对账和关税状态不为已关税
                cond.where("A.status = 3 OR A.tariffZfStatus = 1");
            }
            //创建时间
            String _ys_createTime = ConditionUtil.getConditionValue(conditions, "_ys_createTime");
            if (_ys_createTime != null && _ys_createTime.length() > 0) {
                String[] timeDays = _ys_createTime.split(" ~ ");
                cond.where("A.CreateTime >= '" + timeDays[0] + "' and A.CreateTime <= '" + timeDays[1] + "'");
            }
            //物流订单利润率（对账）
            String _ys_logOrderMarginDz = ConditionUtil.getConditionValue(conditions, "_ys_logOrderMarginDz");
            if (_ys_logOrderMarginDz != null){
                if (_ys_logOrderMarginDz.equals("0")){
                    //正
                    cond.where("A.logOrderMarginDz >=0");
                }else {
                    //负
                    cond.where("A.logOrderMarginDz <0");
                }
            }
            //物流订单对账说明
            String _ys_logOrderlDesDz = ConditionUtil.getConditionValue(conditions, "_ys_logOrderlDesDz");
            if (_ys_logOrderlDesDz != null){
                if (_ys_logOrderlDesDz.equals("0")){
                    cond.where("A.logOrderlDesDz IS NOT NULL AND A.logOrderlDesDz != ''");
                }else {
                    cond.where("A.logOrderlDesDz IS NULL OR A.logOrderlDesDz = ''");
                }
            }
            cond.addField("CASE WHEN A.logOrderStatusDz = 0  THEN '空' WHEN A.logOrderStatusDz = 1  THEN '盈利' WHEN A.logOrderStatusDz = 2  THEN '低利润'  ELSE '亏损' END logOrderStatusDzName ");//物流订单对账状态
            cond.addField("CASE WHEN A.logPayStatusZf = 0  THEN '空' WHEN A.logPayStatusZf = 1  THEN '未完整'  ELSE '已完整' END logPayStatusZfName ");//物流付款状态
            cond.addField("CASE WHEN A.tariffPayStatus = 0  THEN '空' WHEN A.tariffPayStatus = 1  THEN '未完整'  ELSE '已完整' END tariffPayStatusName ");//关税付款状态
            cond.addField("CASE WHEN A.tariffZfStatus = 0  THEN '无需处理' WHEN A.tariffZfStatus = 1  THEN '待关税'  ELSE '已关税' END tariffZfStatusName ");//关税状态
            cond.addField("CASE WHEN A.status = 3  THEN '物流订单待对账' WHEN A.status = 4  THEN '物流订单已对账'  ELSE '物流订单已付款' END statusName ");//物流状态

            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TCC_LOGISTICSRECONCILE)
                    .setFrontExport(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<TccLogisticsComprehensive> util = new ExportExcelUtils<>(new TccLogisticsComprehensive());
            String toFilePath = util.exportExcel(listData, listField, "物流对账报表");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /*
     * 对账(api)
     */
    @RequiresPermissions(PERMISSIONS_APIDZ)
    @RequestMapping("/apiDz")
    @ResponseBody
    public R apiDz(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        try {
            return tccLogisticsReconcileService.apiDz(params);
        } catch (Exception e) {
            logger.error("对账(api)出错：", e.getMessage(), e);
            return R.error("对账(api)出错,原因如下:" + e.getMessage());
        }
    }
}
